package net.tv90.bfmccore.code;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.opencsv.CSVReader;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Csv2VehicleMenuTest {
    // 路径常量
    private static final String CSV_PATH = "D:\\BFMCCore\\src\\main\\resources\\vehicle_group\\vehicles.csv";
    private static final String DEFAULT_JSON_PATH = "D:\\BFMCCore\\src\\main\\resources\\vehicle_group\\vehicle_details_default.json";
    private static final String OUTPUT_JSON_PATH = "D:\\BFMCCore\\src\\main\\resources\\vehicle_group\\vehicle_details.json";

    // 每行最大字符数（可调整）
    private static final int MAX_LINE_LEN = 27;

    public static void main(String[] args) throws Exception {
        // 1) 读取 CSV（UTF-8）
        VehiclesData csvData = new VehiclesData();
        try (CSVReader csvReader = new CSVReader(
                new InputStreamReader(Files.newInputStream(Paths.get(CSV_PATH)), StandardCharsets.UTF_8))) {

            // 读取表头（第一行列名）
            String[] headers = csvReader.readNext();
            String[] row;

            // 遍历每一行记录
            while ((row = csvReader.readNext()) != null) {
                // 安全检查：列长度不足时跳过
                if (row.length < 13) continue;

                // 根据CSV列顺序提取所需字段
                String name = nv(row[0]);
                String key = nv(row[1]);
                String id = nv(row[2]);
                // 等级 row[3] (如 T1) 可用于描述但这里不单独输出
                String role = nv(row[4]);                 // 定位
                String hpArmor = nv(row[5]);              // 血量/护甲
                String mobility = nv(row[6]);             // 机动性
                String disableThreshold = nv(row[7]);     // 瘫痪阈值
                String primaryWeapon = nv(row[8]);        // 一号位武器
                String secondaryWeapon = nv(row[9]);      // 副驾驶武器
                String specialEquip = nv(row[10]);        // 特殊辅助设备
                String advantages = nv(row[11]);          // 优点
                String disadvantages = nv(row[12]);       // 缺陷

                // 创建 Vehicle 对象
                Vehicle vehicle = new Vehicle(key, name, id);

                // 生成描述信息（包含：中文逗号替换、硬切分、“但是”另起行）
                generateDescription(vehicle.description, role, advantages, disadvantages);

                // 添加装备/武器描述行和固定格式行
                vehicle.description.add("-----------------------------------------");
                vehicle.description.add("&6驾驶员 - " + (primaryWeapon.isEmpty() ? "无" : primaryWeapon.replace(",", "，")));
                vehicle.description.add("&6副驾驶 - " + (secondaryWeapon.isEmpty() ? "无" : secondaryWeapon.replace(",", "，")));
                vehicle.description.add("&6载具配备 - " + (specialEquip.isEmpty() ? "无" : specialEquip.replace(",", "，")));
                vehicle.description.add("&6战斗属性 - 血量/护甲:" + hpArmor.replace(",", "，")
                        + "，机动性:" + mobility.replace(",", "，")
                        + "，瘫痪阈值:" + disableThreshold.replace(",", "，"));
                vehicle.description.add("-----------------------------------------");
                vehicle.description.add("&a点击部署载具");
                // 假设默认已解锁
                vehicle.description.add("&a你已经解锁了该载具");
                // 如需锁定提示，可根据情况: vehicle.description.add("%unlock_xxx%");

                // 将该载具加入列表
                csvData.vehicles.add(vehicle);
            }
        }

        // 2) 读取默认 JSON（UTF-8）
        VehiclesData defaultData = readVehiclesFromJson(DEFAULT_JSON_PATH);

        // 3) 拼接：默认在前，CSV 在后
        VehiclesData merged = new VehiclesData();
        merged.vehicles.addAll(defaultData.vehicles);
        merged.vehicles.addAll(csvData.vehicles);

        // 4) 去重（按 id），让 CSV 覆盖默认：后者覆盖前者
        Map<String, Vehicle> dedup = new LinkedHashMap<>();
        for (Vehicle v : merged.vehicles) {
            // id 为空时也加入，但用 key+name 做兜底 key，避免丢数据
            String k = (v.id != null && !v.id.isEmpty()) ? v.id : (v.key + "|" + v.name);
            dedup.put(k, v);
        }
        merged.vehicles = new ArrayList<>(dedup.values());

        // 5) 写出合并后的 JSON（UTF-8）
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        try (OutputStreamWriter writer = new OutputStreamWriter(
                Files.newOutputStream(Paths.get(OUTPUT_JSON_PATH)), StandardCharsets.UTF_8)) {
            gson.toJson(merged, writer);
        }
    }

    private static void generateDescription(List<String> descList, String role,
                                            String advantages, String disadvantages) {
        StringBuilder descBuilder = new StringBuilder();

        descBuilder.append("定位: ").append(role);
        // 根据“定位”决定开头描述
        if (role.contains("反人员")) {
            descBuilder.append("，在清除步兵方面表现出色。");
        } else if (role.contains("反载具")) {
            descBuilder.append("，专注于对抗敌方载具。");
        } else if (role.contains("多用途")) {
            descBuilder.append("，在各方面的能力都较为均衡。");
        } else if (role.contains("快速支援")) {
            descBuilder.append("，在战场上具有灵活的高机动性。");
        } else if (role.contains("巷战特化")) {
            descBuilder.append("，适合在狭窄地形内作战。");
        } else if (role.contains("纯对地")) {
            descBuilder.append("，专注于消灭敌军地面部队。");
        } else if (role.contains("纯制空")) {
            descBuilder.append("，用于在战场上夺取制空权。");
        } else {
            descBuilder.append("。");
        }

        // 拼接优点
        if (advantages != null && !advantages.isEmpty()) {
            descBuilder.append("\n特点: ").append(advantages);
        }
        descBuilder.append("。");

        // 将完整描述转为字符串
        String fullDesc = descBuilder.toString();
        // 如果有缺点，单独换行
        if (disadvantages != null && !disadvantages.isEmpty()) {
            fullDesc = fullDesc + "\n缺点: " + disadvantages + "。";
        }
        fullDesc = fullDesc.replace(",", "，"); // 替换英文逗号为中文逗号
        // 每行最大字符数
        int maxLen = MAX_LINE_LEN;
        // 按换行符和固定长度拆分
        for (String part : fullDesc.split("\n")) {
            for (int i = 0; i < part.length(); i += maxLen) {
                int end = Math.min(i + maxLen, part.length());
                descList.add(part.substring(i, end));
            }
        }
    }

    private static VehiclesData readVehiclesFromJson(String path) {
        try (InputStreamReader reader = new InputStreamReader(
                Files.newInputStream(Paths.get(path)), StandardCharsets.UTF_8)) {
            Gson gson = new Gson();
            Type type = new TypeToken<VehiclesData>() {
            }.getType();
            VehiclesData data = gson.fromJson(reader, type);
            if (data == null) data = new VehiclesData();
            if (data.vehicles == null) data.vehicles = new ArrayList<>();
            return data;
        } catch (Exception e) {
            // 读不到文件或格式异常时，返回空数据结构，避免中断
            VehiclesData empty = new VehiclesData();
            empty.vehicles = new ArrayList<>();
            return empty;
        }
    }

    /**
     * null -> "" 的小工具
     */
    private static String nv(String s) {
        return s == null ? "" : s.trim();
    }

    static class Vehicle {
        String key;
        String name;
        List<String> description;
        String id;

        // 构造方法（省略getter/setter，为简洁起见）
        Vehicle(String key, String name, String id) {
            this.key = key;
            this.name = name;
            this.id = id;
            this.description = new ArrayList<>();
        }
    }

    static class VehiclesData {
        List<Vehicle> vehicles = new ArrayList<>();
    }

}
